import React, { useState, useEffect } from 'react';
import { 
  Typography, 
  Input, 
  Button, 
  Form,
  Spin, 
  Alert, 
  Card, 
  Tabs, 
  List, 
  Tag, 
  Divider, 
  Space,
  Row,
  Col,
  Select,
  Radio,
  Collapse,
  Timeline,
  Tooltip,
  Badge,
  message
} from 'antd';
import {
  SendOutlined,
  InfoCircleOutlined,
  WarningOutlined,
  CheckCircleOutlined,
  UserOutlined,
  TeamOutlined,
  SolutionOutlined,
  MessageOutlined,
  BulbOutlined,
  EnvironmentOutlined,
  QuestionCircleOutlined
} from '@ant-design/icons';
import { ShieldOutlined } from '../components/icons/IconComponents';
import puaService from '../api/puaService';
import chatService from '../api/chatService';

const { Title, Paragraph, Text } = Typography;
const { TextArea } = Input;
const { TabPane } = Tabs;
const { Option } = Select;
const { Panel } = Collapse;

const PUAAdvancedAnalysisPage = () => {
  const [form] = Form.useForm();
  const [content, setContent] = useState('');
  const [loading, setLoading] = useState(false);
  const [result, setResult] = useState(null);
  const [contextMessages, setContextMessages] = useState([]);
  const [loadingContextMessages, setLoadingContextMessages] = useState(false);
  const [selectedContact, setSelectedContact] = useState(null);
  const [selectedSession, setSelectedSession] = useState(null);
  const [contacts, setContacts] = useState([]);
  const [sessions, setSessions] = useState([]);
  
  // 获取联系人和会话数据
  useEffect(() => {
    const fetchData = async () => {
      try {
        // 模拟数据获取
        setTimeout(() => {
          setContacts([
            { id: 1, name: '张三', avatar: 'https://via.placeholder.com/40' },
            { id: 2, name: '李四', avatar: 'https://via.placeholder.com/40' },
            { id: 3, name: '王五', avatar: 'https://via.placeholder.com/40' }
          ]);
          
          setSessions([
            { id: 101, name: '工作群', type: 'group', avatar: 'https://via.placeholder.com/40' },
            { id: 102, name: '家庭群', type: 'group', avatar: 'https://via.placeholder.com/40' }
          ]);
        }, 500);
        
        // 实际API调用
        // const contactsData = await contactsService.getContacts();
        // const sessionsData = await chatService.getSessions();
        // setContacts(contactsData);
        // setSessions(sessionsData);
      } catch (error) {
        console.error('获取联系人和会话数据失败:', error);
        message.error('获取联系人和会话数据失败');
      }
    };
    
    fetchData();
  }, []);

  // 加载上下文消息
  const loadContextMessages = async () => {
    if (!selectedContact && !selectedSession) return;
    
    setLoadingContextMessages(true);
    setContextMessages([]);
    
    try {
      // 模拟数据获取
      setTimeout(() => {
        const mockMessages = [
          { 
            id: 1, 
            role: 'user', 
            content: '你今天去参加那个活动了没？我还以为会看到你呢。', 
            timestamp: '2023-08-10T10:15:00Z' 
          },
          { 
            id: 2, 
            role: 'sender', 
            content: '没去成，临时有事。怎么了？', 
            timestamp: '2023-08-10T10:20:00Z' 
          },
          { 
            id: 3, 
            role: 'user', 
            content: '没什么，就是感觉你最近好像总是有事，约你几次了都见不到面。', 
            timestamp: '2023-08-10T10:25:00Z' 
          },
          { 
            id: 4, 
            role: 'sender', 
            content: '是吗？可能最近确实比较忙吧。', 
            timestamp: '2023-08-10T10:30:00Z' 
          },
          { 
            id: 5, 
            role: 'user', 
            content: '你朋友圈还发了照片，看起来挺开心的，应该不是真的有事吧？你是不是不想见我？', 
            timestamp: '2023-08-10T10:35:00Z' 
          }
        ];
        
        setContextMessages(mockMessages);
        setLoadingContextMessages(false);
      }, 1000);
      
      // 实际API调用
      // const params = selectedContact 
      //   ? { contact_id: selectedContact, limit: 10 }
      //   : { session_id: selectedSession, limit: 10 };
      // const messagesData = await chatService.getMessages(params);
      // setContextMessages(messagesData);
    } catch (error) {
      console.error('加载上下文消息失败:', error);
      message.error('加载上下文消息失败');
      setLoadingContextMessages(false);
    }
  };

  // 提交分析请求
  const handleSubmit = async (values) => {
    setLoading(true);
    setResult(null);
    
    try {
      // 准备上下文消息
      const context = contextMessages.map(msg => ({
        role: msg.role,
        content: msg.content
      }));
      
      // 调用API
      // 实际项目中取消下面的模拟代码，使用真实API调用
      setTimeout(() => {
        const mockResult = {
          detection_result: {
            is_pua: true,
            score: 0.85,
            risk_level: "medium",
            detected_patterns: [
              {
                category: "guilt_tripping",
                description: "制造罪恶感来控制对方行为",
                severity: 0.8,
                evidence: "你是不是不想见我？",
                manipulation_tactics: "通过质疑对方的意图，使其产生愧疚感"
              },
              {
                category: "gaslighting",
                description: "让对方怀疑自己的感受和判断",
                severity: 0.7,
                evidence: "你朋友圈还发了照片，看起来挺开心的，应该不是真的有事吧？",
                manipulation_tactics: "通过挑战对方的解释，让其怀疑自己的说法"
              }
            ],
            explanation: "文本中包含明显的罪恶感操纵和煤气灯效应。发送者试图通过质疑接收者的意图和行为，让接收者产生愧疚感，同时挑战接收者的解释，让其怀疑自己的说法。",
            response_suggestions: [
              "我理解你可能感到失望，但我确实有其他安排，我们可以改天再约。",
              "我的时间安排是我的个人选择，希望你能尊重这一点。",
              "我们可以坦诚地交流期望，但请不要质疑我的诚意。"
            ],
            long_term_advice: "这种模式如果经常出现，可能表明对方在尝试通过情感操控来影响你的行为。建议设立明确的个人边界，并坚持自己的决定。",
            emotional_impact: "这类言论可能导致你感到愧疚、困惑和自我怀疑，长期可能损害自尊心和自主性。"
          },
          deep_analysis: {
            detected_categories: ["guilt_tripping", "gaslighting"],
            personalized_advice: {
              age_specific: values.ageGroup === "teen" 
                ? "作为年轻人，建议你与信任的成年人(如父母、老师或辅导员)分享这些信息，获取支持和建议。" 
                : "了解这些模式可以帮助你在人际关系中维护健康界限。",
              context_specific: values.relationshipContext === "dating" 
                ? "在约会关系中，健康的互动应该建立在平等、尊重和良好沟通的基础上。" 
                : "友谊应当是支持和积极的，任何试图控制或贬低你的行为都值得重新评估这段关系。",
              general_strategies: [
                "可以明确表达：'我需要我们的关系建立在相互尊重的基础上'",
                "当感到不舒服时，可以说：'我需要一些时间思考这个问题'"
              ],
              safety_tips: [
                "信任你的直觉，如果某段对话让你感到不适，这可能是一个重要的警示信号",
                "设立并坚守你的个人界限，不要因为压力而妥协"
              ]
            },
            educational_resources: [
              {
                title: "识别情感操控",
                description: "学习如何识别常见的情感操控手段",
                url: "https://example.com/emotional-manipulation",
                type: "article"
              },
              {
                title: "设立健康边界",
                description: "关于如何在人际关系中设立健康边界的指南",
                url: "https://example.com/healthy-boundaries",
                type: "guide"
              }
            ],
            priority_focus: values.priority,
            long_term_advice: "在恋爱关系中，注意观察模式而非单一事件。如果操控行为形成模式，应考虑关系的健康度。"
          }
        };
        
        setResult(mockResult);
        setLoading(false);
      }, 1500);
      
      // 实际API调用示例：
      // const response = await puaService.analyzeAndRespond(
      //   values.content,
      //   values.ageGroup,
      //   values.relationshipContext,
      //   values.priority,
      //   context.length > 0 ? context : null
      // );
      // setResult(response.data);
    } catch (error) {
      console.error('PUA详细分析失败:', error);
      message.error('PUA详细分析失败，请稍后重试');
      setLoading(false);
    }
  };

  // 根据风险等级获取颜色
  const getRiskColor = (level) => {
    switch(level) {
      case 'high': return 'red';
      case 'medium': return 'orange';
      case 'low': return 'green';
      default: return 'default';
    }
  };

  // 根据风险等级获取图标
  const getRiskIcon = (level) => {
    switch(level) {
      case 'high': return <WarningOutlined />;
      case 'medium': return <InfoCircleOutlined />;
      case 'low': return <CheckCircleOutlined />;
      default: return <QuestionCircleOutlined />;
    }
  };

  return (
    <div className="pua-advanced-analysis-page">
      <Title level={2}>
        <Space>
          <ShieldOutlined />
          PUA详细分析
        </Space>
      </Title>
      <Paragraph>
        提供更深入的PUA行为分析和个性化建议，帮助您更好地理解和应对复杂的沟通情境。
      </Paragraph>
      
      <Card>
        <Tabs defaultActiveKey="content">
          <TabPane 
            tab={<span><MessageOutlined />直接分析文本</span>}
            key="content"
          >
            <Form
              form={form}
              layout="vertical"
              onFinish={handleSubmit}
              initialValues={{
                content: '',
                ageGroup: 'adult',
                relationshipContext: 'friendship',
                priority: 'balanced'
              }}
            >
              <Form.Item
                name="content"
                label="需要分析的文本内容"
                rules={[{ required: true, message: '请输入要分析的文本内容' }]}
              >
                <TextArea 
                  rows={6} 
                  placeholder="请输入可能含有PUA内容的文本..." 
                  onChange={e => setContent(e.target.value)}
                />
              </Form.Item>
              
              <Row gutter={16}>
                <Col xs={24} sm={24} md={8}>
                  <Form.Item
                    name="ageGroup"
                    label={
                      <span>
                        年龄组 
                        <Tooltip title="不同年龄段的用户可能需要不同的应对策略">
                          <QuestionCircleOutlined style={{ marginLeft: 4 }} />
                        </Tooltip>
                      </span>
                    }
                  >
                    <Select>
                      <Option value="teen">青少年</Option>
                      <Option value="adult">成年人</Option>
                      <Option value="elderly">老年人</Option>
                    </Select>
                  </Form.Item>
                </Col>
                <Col xs={24} sm={24} md={8}>
                  <Form.Item
                    name="relationshipContext"
                    label={
                      <span>
                        关系背景
                        <Tooltip title="您与发送消息者的关系类型">
                          <QuestionCircleOutlined style={{ marginLeft: 4 }} />
                        </Tooltip>
                      </span>
                    }
                  >
                    <Select>
                      <Option value="dating">约会/恋爱关系</Option>
                      <Option value="friendship">朋友关系</Option>
                      <Option value="professional">职场关系</Option>
                      <Option value="family">家庭关系</Option>
                    </Select>
                  </Form.Item>
                </Col>
                <Col xs={24} sm={24} md={8}>
                  <Form.Item
                    name="priority"
                    label={
                      <span>
                        分析优先级
                        <Tooltip title="分析结果的优先关注点">
                          <QuestionCircleOutlined style={{ marginLeft: 4 }} />
                        </Tooltip>
                      </span>
                    }
                  >
                    <Radio.Group>
                      <Radio value="safety">安全</Radio>
                      <Radio value="education">教育</Radio>
                      <Radio value="balanced">平衡</Radio>
                    </Radio.Group>
                  </Form.Item>
                </Col>
              </Row>
              
              {/* 上下文消息选择 */}
              <Divider orientation="left">上下文消息(选填)</Divider>
              <Row gutter={16} style={{ marginBottom: 16 }}>
                <Col xs={24} sm={12}>
                  <Select
                    placeholder="选择联系人加载上下文消息"
                    style={{ width: '100%' }}
                    allowClear
                    onChange={value => {
                      setSelectedContact(value);
                      setSelectedSession(null);
                    }}
                  >
                    {contacts.map(contact => (
                      <Option key={contact.id} value={contact.id}>
                        <UserOutlined /> {contact.name}
                      </Option>
                    ))}
                  </Select>
                </Col>
                <Col xs={24} sm={12}>
                  <Select
                    placeholder="选择会话加载上下文消息"
                    style={{ width: '100%' }}
                    allowClear
                    onChange={value => {
                      setSelectedSession(value);
                      setSelectedContact(null);
                    }}
                  >
                    {sessions.map(session => (
                      <Option key={session.id} value={session.id}>
                        <TeamOutlined /> {session.name}
                      </Option>
                    ))}
                  </Select>
                </Col>
              </Row>
              
              <Button 
                type="dashed" 
                block 
                onClick={loadContextMessages}
                loading={loadingContextMessages}
                disabled={!selectedContact && !selectedSession}
              >
                加载上下文消息
              </Button>
              
              {contextMessages.length > 0 && (
                <Card 
                  size="small" 
                  title="上下文消息" 
                  style={{ marginTop: 16, marginBottom: 16 }}
                >
                  <Timeline>
                    {contextMessages.map(message => (
                      <Timeline.Item 
                        key={message.id}
                        color={message.role === 'user' ? 'blue' : 'green'}
                      >
                        <p>
                          <Text strong>
                            {message.role === 'user' ? '对方' : '我'}：
                          </Text>
                          {message.content}
                        </p>
                        <Text type="secondary" style={{ fontSize: 12 }}>
                          {new Date(message.timestamp).toLocaleString()}
                        </Text>
                      </Timeline.Item>
                    ))}
                  </Timeline>
                </Card>
              )}
              
              <Form.Item>
                <Button 
                  type="primary" 
                  htmlType="submit" 
                  icon={<SendOutlined />} 
                  loading={loading}
                  disabled={!form.getFieldValue('content')}
                  block
                >
                  提交分析
                </Button>
              </Form.Item>
            </Form>
          </TabPane>
        </Tabs>
      </Card>
      
      {/* 分析结果展示 */}
      {result && (
        <div style={{ marginTop: 24 }}>
          <Card 
            title={
              <Space>
                <Badge 
                  status={result.detection_result.is_pua ? "error" : "success"} 
                />
                <span>PUA详细分析结果</span>
                {result.detection_result.is_pua && (
                  <Tag color={getRiskColor(result.detection_result.risk_level)}>
                    {getRiskIcon(result.detection_result.risk_level)}
                    <span style={{ marginLeft: 4 }}>
                      {result.detection_result.risk_level === 'high' && "高风险"}
                      {result.detection_result.risk_level === 'medium' && "中等风险"}
                      {result.detection_result.risk_level === 'low' && "低风险"}
                    </span>
                  </Tag>
                )}
              </Space>
            }
          >
            <Row gutter={[24, 24]}>
              <Col xs={24}>
                <Alert
                  message={result.detection_result.is_pua ? "检测到PUA内容" : "未检测到明显PUA内容"}
                  description={result.detection_result.explanation}
                  type={result.detection_result.is_pua ? "warning" : "success"}
                  showIcon
                />
              </Col>
              
              {result.detection_result.is_pua && (
                <>
                  <Col xs={24} md={12}>
                    <Card 
                      title="检测到的PUA模式" 
                      size="small" 
                      className="analysis-card"
                    >
                      <List
                        itemLayout="horizontal"
                        dataSource={result.detection_result.detected_patterns}
                        renderItem={pattern => (
                          <List.Item>
                            <List.Item.Meta
                              title={
                                <Space>
                                  <Tag color="magenta">{pattern.category}</Tag>
                                  <Text strong>{pattern.description}</Text>
                                  <Tag color={pattern.severity > 0.7 ? "red" : "orange"}>
                                    严重度: {(pattern.severity * 10).toFixed(1)}
                                  </Tag>
                                </Space>
                              }
                              description={
                                <>
                                  <Paragraph>
                                    <Text strong>证据：</Text>
                                    <Text mark>{pattern.evidence}</Text>
                                  </Paragraph>
                                  <Paragraph>
                                    <Text strong>操控策略：</Text>
                                    {pattern.manipulation_tactics}
                                  </Paragraph>
                                </>
                              }
                            />
                          </List.Item>
                        )}
                      />
                    </Card>
                  </Col>
                  
                  <Col xs={24} md={12}>
                    <Card 
                      title="情感影响与长期建议" 
                      size="small" 
                      className="analysis-card"
                    >
                      <Paragraph>
                        <Text strong>情感影响：</Text>
                        {result.detection_result.emotional_impact}
                      </Paragraph>
                      <Paragraph>
                        <Text strong>长期建议：</Text>
                        {result.detection_result.long_term_advice || result.deep_analysis.long_term_advice}
                      </Paragraph>
                    </Card>
                  </Col>
                </>
              )}
              
              <Col xs={24}>
                <Collapse defaultActiveKey={['1', '2']} expandIconPosition="right">
                  <Panel 
                    header={
                      <Space>
                        <ShieldOutlined />
                        <span>建议回应方式</span>
                      </Space>
                    } 
                    key="1"
                  >
                    <List
                      bordered
                      dataSource={result.detection_result.response_suggestions}
                      renderItem={(suggestion, index) => (
                        <List.Item>
                          <Badge count={index + 1} style={{ backgroundColor: '#52c41a' }} />
                          <span style={{ marginLeft: 12 }}>{suggestion}</span>
                        </List.Item>
                      )}
                    />
                  </Panel>
                  
                  <Panel 
                    header={
                      <Space>
                        <SolutionOutlined />
                        <span>个性化建议</span>
                      </Space>
                    } 
                    key="2"
                  >
                    <div className="personalized-advice">
                      <Row gutter={[16, 16]}>
                        <Col xs={24}>
                          <Card size="small" title="年龄相关建议">
                            {result.deep_analysis.personalized_advice.age_specific}
                          </Card>
                        </Col>
                        <Col xs={24}>
                          <Card size="small" title="关系背景相关建议">
                            {result.deep_analysis.personalized_advice.context_specific}
                          </Card>
                        </Col>
                        <Col xs={24} md={12}>
                          <Card size="small" title="一般应对策略">
                            <List
                              size="small"
                              dataSource={result.deep_analysis.personalized_advice.general_strategies}
                              renderItem={strategy => (
                                <List.Item>
                                  <BulbOutlined style={{ marginRight: 8 }} />
                                  {strategy}
                                </List.Item>
                              )}
                            />
                          </Card>
                        </Col>
                        <Col xs={24} md={12}>
                          <Card size="small" title="安全提示">
                            <List
                              size="small"
                              dataSource={result.deep_analysis.personalized_advice.safety_tips}
                              renderItem={tip => (
                                <List.Item>
                                  <ShieldOutlined style={{ marginRight: 8 }} />
                                  {tip}
                                </List.Item>
                              )}
                            />
                          </Card>
                        </Col>
                      </Row>
                    </div>
                  </Panel>
                  
                  <Panel 
                    header={
                      <Space>
                        <EnvironmentOutlined />
                        <span>教育资源</span>
                      </Space>
                    } 
                    key="3"
                  >
                    <List
                      itemLayout="horizontal"
                      dataSource={result.deep_analysis.educational_resources}
                      renderItem={resource => (
                        <List.Item
                          actions={[
                            <a href={resource.url} target="_blank" rel="noopener noreferrer">
                              查看
                            </a>
                          ]}
                        >
                          <List.Item.Meta
                            title={resource.title}
                            description={resource.description}
                          />
                          <Tag color="blue">{resource.type}</Tag>
                        </List.Item>
                      )}
                    />
                  </Panel>
                </Collapse>
              </Col>
            </Row>
          </Card>
        </div>
      )}
    </div>
  );
};

export default PUAAdvancedAnalysisPage; 